package com.seo.textgen.markov;

import com.seo.textgen.tokenizer.Token;

public class Chain {

	public Token[] tokens;

	private String string;

	private int start;

	private int len;

	private int hashCode;

	public Chain(Token[] tokens, int start, int len) {
		this.tokens = tokens;
		this.start = start;
		this.len = len;

		string = getString();
		hashCode = string.hashCode();
	}

	private String getString() {
		StringBuilder sb = new StringBuilder();
		for (int i = start; i < start + len; i++) {
			if (i != start) {
				sb.append(" ");
			}
			if (i < 0) {
				sb.append(Token.EMPTY_TOKEN.getToken());
			} else {
				sb.append(tokens[i].getToken());
			}
		}
		return sb.toString();
	}

	@Override
	public int hashCode() {
		return hashCode;
	}

	@Override
	public boolean equals(Object obj) {
		return ((Chain) obj).string.equals(string);
	}

	@Override
	public String toString() {
		return string;
	}

	public Chain getSubChain() {
		return new Chain(tokens, start, len - 1);
	}

	public Token getLastToken() {
		return tokens[start + len - 1];
	}
}
